use crate::commands::jdocker::Jdocker;
use nix::libc::exit;
use std::fs;
use std::fs::{exists, File, OpenOptions};
use std::io::{Read, Write};
use std::path::Path;
use crate::utilty::{get_image_name_and_container_name_from_file_name, pid_is_alive};

//ok
pub fn ps() {
    unsafe {
        let jdocker = Jdocker::new().get_db_dir();
        let db_dir_path = Path::new(jdocker.as_str());
        let dir = db_dir_path
            .read_dir()
            .expect("Error reading directory");
        dir.for_each(|e| {
            if let Ok(file) = e{
                let file_name = file.file_name().into_string().unwrap();
                let (image_name,container_name) = get_image_name_and_container_name_from_file_name(file_name);
                match File::open(file.path()) {
                    Ok(mut f) => {
                        let mut buf = String::new();
                        f.read_to_string(&mut buf).unwrap();
                        if buf.is_empty() {
                            buf.push_str("no pid")
                        }else if !pid_is_alive(buf.clone()) {
                            buf.clear();
                            buf.push_str("no pid")
                        }
                        println!("image name: {} container name: {} pid: {}", &image_name, &container_name,buf);
                    }
                    Err(e) => { println!("{}", e); }
                }
            };
        })
    }
}
